﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using MyMainSite2.Data;
using MyMainSite2.Data.Repositories;
using MyMainSite2.Library.MVC;
using MyMainSite2.UI.AdminWeb.Helpers;
using MyMainSite2.UI.AdminWeb.Models.Admin;

namespace MyMainSite2.UI.AdminWeb.Controllers
{
	public class AdminController : Controller
	{
		#region Public Methods

		[Authorize]
		public ActionResult Index()
		{
			return this.View();
		}

		public ActionResult Login()
		{
			return this.View();
		}

		[Authorize]
		public RedirectResult Logout()
		{
			FormsAuthenticationHelperFactory.Helper.Logout();

			return this.Redirect("/");
		}

		public JSONResult DoLogin(string userName, string password)
		{
			try
			{
				if (String.IsNullOrWhiteSpace(userName))
					throw new ArgumentNullException("userName");

				if (String.IsNullOrWhiteSpace(password))
					throw new ArgumentNullException("password");

				var repo = AdminUserRepositoryFactory.Repository;

				var isValidUser = repo.ValidateUserNameAndPassword(userName, password);
				if (!isValidUser)
				{
					throw new InvalidOperationException("Invalid User Name or Password.");
				}

				FormsAuthenticationHelperFactory.Helper.Login(this.ControllerContext, userName);
			}
			catch (Exception ex)
			{
				return new JSONResult(ex);
			}

			return new JSONResult(new object { });
		}

		public PartialViewResult UserInformation()
		{
			var model = new UserInformationModel();

			var userName = this.ControllerContext.HttpContext.User.Identity.Name;

			if (String.IsNullOrEmpty(userName))
			{
				model.Name = "Your are not logged in.";
			}
			else
			{
				var user = AdminUserRepositoryFactory.Repository.GetByUserName(userName);

				model.Name = String.Format("{0} {1}", user.FirstName, user.LastName);
			}

			return this.PartialView(model);
		}

		public PartialViewResult SideMenu()
		{
			var model = new SideMenuModel();

			var userName = this.ControllerContext.HttpContext.User.Identity.Name;

			if (!String.IsNullOrWhiteSpace(userName))
			{
				model.IsLoggedIn = true;

				var user = AdminUserRepositoryFactory.Repository.GetByUserName(userName);

				foreach (var role in user.tblAdminRoles)
				{
					if (role.Name == "Page_Create")
					{
						model.HasPageRoles = true;
						model.HasPageCreate = true;
					}
					else if (role.Name == "Page_Read")
					{
						model.HasPageRoles = true;
						model.HasPageRead = true;
					}
				}
			}

			return this.PartialView(model);
		}

		[Authorize]
		public ViewResult YourProfile()
		{
			var userName = this.ControllerContext.HttpContext.User.Identity.Name;

			var user = AdminUserRepositoryFactory.Repository.GetByUserName(userName);

			return this.View(new YourProfileModel()
							 {
								 FirstName = user.FirstName,
								 LastName = user.LastName,
							 });
		}

		[Authorize]
		[HttpPost]
		public JSONResult YourProfile(YourProfileModel model)
		{
			try
			{
				if (!this.ModelState.IsValid)
					throw new InvalidOperationException("Invaild Model State");

				var factory = AdminUserRepositoryFactory.Repository;

				var userName = this.ControllerContext.HttpContext.User.Identity.Name;

				var user = factory.GetByUserName(userName);

				user.FirstName = model.FirstName;
				user.LastName = model.LastName;

				var result = factory.UpdateUser(user);
				if (!result)
					throw new InvalidOperationException("Failed to update Admin User");

				return new JSONResult(new
									  {
										  firstName = user.FirstName,
										  lastName = user.LastName,
									  });
			}
			catch (Exception ex)
			{
				return new JSONResult(ex);
			}
		}

		#endregion
	}
}
